﻿using Delphi.Mimir.Config;
using Delphi.Mimir.Data.Entities.Final;
using Delphi.Mimir.Data.Entities.Final.Helpers;
using System.Collections.Generic;
using System.Linq;

namespace Delphi.Mimir.Wrapper {
    public class ExchangeWrapper {
        public static ICollection<Exchange> GetExchanges() {
            ICollection<Exchange> excs = new List<Exchange>();
            using(var context = new DelphiContext()) {
                excs = context.Exchanges.ToList<Exchange>();
            }
            return excs;
        }

        public static Exchange GetExchange(string exchangeCode) {
            Exchange exc = new Exchange();
            using(var context = new DelphiContext()) {
                exc = context.Exchanges.Where(e => e.Code == exchangeCode).FirstOrDefault();
            }
            return exc;
        }

        public static ICollection<ExchangeLastLoad> GetLastLoads() {
            ICollection<ExchangeLastLoad> excs = new List<ExchangeLastLoad>();
            using(var context = new DelphiContext()) {
                excs = context.Exchanges.Select(a => new ExchangeLastLoad {
                    ExchangeCode = a.Code,
                    HasIntraDayProduct = a.HasIntraDayProduct,
                    Timezone = a.TimeZone,
                    LocalClosingHour = a.LocalClosingHour,
                    LastControls = a.LoadControls.Select(b => new ExchangeLastLoad.LastLoadControls {
                        LoadTypeCode = b.LoadType.Code,
                        LoadControlId = b.LoadControlId,
                        loadOffset = b.TimeOffset,
                        LastLoad = b.Loads.OrderByDescending(c => c.TradeDate).Where(c => c.Status == "Success").FirstOrDefault()
                    })
                }).ToList();
            }
            return excs;
        }
    }
}
